import React, { useRef, useEffect } from 'react';
import { useAIChat } from '@/contexts/aiChat';
import MessageBubble from '@/components/aiChat/MessageBubble';

/**
 * 消息列表组件
 * 显示聊天历史记录，支持自动滚动到最新消息
 */
const MessageList: React.FC = () => {
  const { getCurrentMessages, isTyping } = useAIChat();
  const messages = getCurrentMessages();
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // 自动滚动到最新消息
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  return (
    <div className="flex-1 overflow-y-auto p-3 space-y-3 h-full">
      <div className="min-h-full">
        {messages.length === 0 ? (
          <div className="h-full flex items-center justify-center text-muted-foreground text-sm">
            选择或开始一个新对话
          </div>
        ) : (
          <>
            {messages.map((message) => (
              <MessageBubble 
                key={message.id}
                message={message}
              />
            ))}
            
            {/* 显示AI正在输入的状态 */}
            {isTyping && (
              <div className="flex items-start max-w-[80%]">
                <div className="bg-accent rounded-lg p-2 text-foreground">
                  <div className="flex space-x-1">
                    <span className="animate-bounce">●</span>
                    <span className="animate-bounce" style={{ animationDelay: '0.2s' }}>●</span>
                    <span className="animate-bounce" style={{ animationDelay: '0.4s' }}>●</span>
                  </div>
                </div>
              </div>
            )}
          </>
        )}
        
        {/* 用于自动滚动的空 div */}
        <div ref={messagesEndRef} />
      </div>
    </div>
  );
};

export default MessageList;
